#!/usr/bin/env python
## Copyright (C) 2010, Scott W. Dunlop <swdunlop@gmail.com>
## All rights reserved.
## 
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
##    * Redistributions of source code must retain the above copyright
##      notice, this list of conditions and the following disclaimer.
##    * Redistributions in binary form must reproduce the above copyright
##      notice, this list of conditions and the following disclaimer in the
##      documentation and/or other materials provided with the distribution.
##    * Neither the name of the <organization> nor the
##      names of its contributors may be used to endorse or promote products
##      derived from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
## ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
## DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 
## THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
This NoSpex demonstration reads hops from one or more LFT traces, and graphs them.  Nodes, here, are IPv4 addresses, strung with links.  This becomes interesting when plotting multiple chains from multiple traces.
"""

import gtk, threading, time, re, subprocess
from cStringIO import StringIO
from nospex import *

def spawn( procedure ):
    threading.Thread( target=procedure ).start( )

def make_line_reader( data ):
    if isinstance( data, str ):
        return StringIO( data ).readline
    elif hasattr( data, 'readline' ):
        return data.readline
    else:
        raise LftError( "Cannot create a data line source from %r" % data )

class LftError( Exception ):
    pass

class LftHudGraph( NoSpexGraph ):
    def __init__( self, *args ):
        NoSpexGraph.__init__( self, *args )
        self.initRoot( )
        self.nodeTable = { "root" : self.root }
    
    def resolveLink( self, source, dest ):
        source = self.resolveNode( source )
        dest = self.resolveNode( dest )
        return source.resolveLink( dest )

    def resolveNode( self, addr ):
        if isinstance( addr, LftHudNode ):
            return addr

        node = self.nodeTable.get( addr )
        if node is None:
            node = self.createNode( addr )
            self.nodeTable[ addr ] = node
        return node
    
    def createNode( self, addr ):
        return LftHudNode( self, addr )

    def initRoot( self ):
        self.root = LftRootNode( self )
    
    def createPing( self, path, source_index ):
        dest_index = source_index + 1
        if dest_index >= len( path ):
            return
        
        source_node = path[source_index]
        dest_node = path[dest_index]

        link = self.resolveLink( source_node, dest_node )
        blip = LftHudBlip( link, 300, path, dest_index )

class LftHudNode( NoSpexNode ):
    #TODO: handleUnlink should remove this node from nodeTables.
    def __init__( self, graph, addr, name = None, rootPath = None ):
        NoSpexNode.__init__( self, graph )
        self.linkTable = {}
        self._name = name
        self._addr = addr
        self.rootPath = rootPath

    def createInfo( self ):
        self.info = str( self.addr )
        return

        if self.name and self.addr:
            self.info = "%s\r(%s)" % ( self.addr, self.name ) 
        elif self.addr:
            self.info = str( self.addr )
        else:
            self.info = "(%s)" % self.name

    @property
    def addr( self ):
        return self._addr
    @addr.setter
    def addr( self, addr ):
        self._addr = addr
        if self.info is not None:
            self.createInfo( )
    
    @property
    def name( self ):
        return self._name
    @name.setter
    def name( self, name ):
        self._name = name
        if self.info is not None:
            self.createInfo( )
    
    def resolveLink( self, node ):
        link = self.linkTable.get( node.addr )
        if link is not None: return link

        link = node.linkTable.get( self.addr )
        if link is not None: return link
    
        link = LftHudLink( self, node )
        self.linkTable[ node.addr ] = link
        node.linkTable[ self.addr ] = link

        return link

    def handleEnter( self ):
        self.createInfo( )

    def handleLeave( self ):
        if not self.isRoot: del self.info 
    
    def handleClick( self ):
        if not self.isEndpoint:
            return
        
        self.graph.createPing( self.rootPath, 0 )
    
    isRoot = False
    
    @property
    def isEndpoint( self ):
        return self.rootPath != None

class LftRootNode( LftHudNode ):
    def __init__( self, graph ):
        LftHudNode.__init__( self, graph, None )
        self.info = "origin"

    def createInfo( self ):
        return

    isRoot = True

class LftHudLink( NoSpexLink ):
    #TODO: handleUnlink should remove this link from linkTables.
    pass

#TODO: Need to set up LftHudBlip so it is link direction agnostic.
class LftHudBlip( NoSpexBlip ):
    def __init__( self, link, duration, path, index ):
        self.path = path
        self.index = index
        NoSpexBlip.__init__( self, link, duration )

    def handleUnlink( self ):
        self.graph.createPing( self.path, self.index )

class LftHud:
    def __init__( self ):
        gtk.gdk.threads_init( )
        self.graph = LftHudGraph( )
    
    def run( self ):
        self.graph.display( )

    def handleHop( self, src_addr, dest_addr, dest_name = None ):
        with control:
            if not src_addr:
                src_node = self.graph.root
            else:
                src_node = self.graph.resolveNode( src_addr )
            
            dest_node = self.graph.resolveNode( dest_addr ) 
            link = src_node.resolveLink( dest_node )
            if dest_name:
                dest_node.name = dest_name
    
    def handleEnd( self, end_addr, root_path ):
        with control:
            if not end_addr: return
            end_node = self.graph.resolveNode( end_addr )
            if not end_node: return
            end_node.rootPath = map( self.graph.resolveNode, root_path )
    
RX_HOST_AND_ADDR = re.compile(
    "^ *[0-9]+"
    " *(?:\\[target\\])?"
    " *([A-Za-z0-9-.]+)"
    " *\\(([0-9.]+)\\)" #" # ([0-9.]+) [0-9.]+ms" 
)

RX_JUST_ADDR = re.compile(
    "^ *[0-9]+"
    " *(?:\\[target\\])?"
    " *([0-9.]+)" #" # ([0-9.]+) [0-9.]+ms" 
)

class LftProcessor( threading.Thread ):
    def __init__( self, hud ):
        self.hud = hud
        self.lastAddr = None
        self.rootPath = [ ]
        threading.Thread.__init__( self )

    def modelHop( self, dest_addr, dest_name = None ):
        time.sleep( 0.01 )
        self.hud.handleHop( self.lastAddr, dest_addr, dest_name )
        self.lastAddr = dest_addr
        self.rootPath.append( dest_addr )
    
    def modelEnd( self ):
        time.sleep( 0.01 )
        if self.lastAddr:
            self.rootPath.reverse()
            self.hud.handleEnd( self.lastAddr, self.rootPath )
    
    def parseLine( self, line ):
        result = RX_HOST_AND_ADDR.match( line )
        if result:
            return self.modelHop( result.group( 2 ), result.group( 1 ) )
            
        result = RX_JUST_ADDR.match( line )
        if result:
            return self.modelHop( result.group( 1 ), None )

    def run( self ):
        while True:
            line = self.readline( )
            if not line: break
            self.parseLine( line )

        self.modelEnd( )

class LftReader( LftProcessor ):
    def __init__( self, hud, data ):
        LftProcessor.__init__( self, hud )
        self.hud = hud
        if data is not None:
            self.readline = make_line_reader( data )
    
class LftProcess( LftProcessor ):
    def __init__( self, hud, host ):
        LftProcessor.__init__( self, hud )
        self.host = host

    def run( self ):
        print "Performing Level Four Trace for %s.." % self.host
        proc = subprocess.Popen(
            ("sudo", "lft", "-S", self.host ),
            stdout=subprocess.PIPE
        )

        self.readline = proc.stdout.readline
        LftProcessor.run( self )

        if not proc.poll():
            self.modelEnd( )
            print "Level Four Trace for %s completed successfully." % self.host
        else:
            print "Level Four Trace for %s failed." % self.host

"""
The model is multiple reader threads feeding data to the HUD; the control 
lock is used to broker access to the HUD, since SDL is not terribly aware of
other threads and NoSpex's display model relies on SDL.

Since the HUD does not synchronously interact with the readers, there should be
no deadlocks.

[ READER 1 ] ----+
[ READER 2 ] ----+---> [ HUD ]
      :          |
[ READER N ] ----+

"""


def main( ):
    # We permit the Gtk thread to take over the main thread of execution; this
    # keeps Gtk out of our hair..
    hud = LftHud( )

    # Our reader, however, runs in its own thread, so it can block on reading
    # data.  It will transmit to the HUD using handleMessage with the GDK 
    # thread lock to prevent state clashes.
    LftReader( hud, open( "data/trace1.txt" ) ).start( )
    LftReader( hud, open( "data/trace2.txt" ) ).start( )
    LftReader( hud, open( "data/trace3.txt" ) ).start( )
    spawn( hud.run )
    #LftProcess( hud, "slashdot.org" ).start( )

if __name__ == "__main__":
    main( )


